<template>
  <a-card class="general-card" title="商品订单" :bordered="false">
    <a-tabs @change="(val)=>{previewParams.orderStatus = val;}" :default-active-key="orderStatus">
      <a-tab-pane key="ALL" title="全部"></a-tab-pane>
      <a-tab-pane key="UNPAID" :title="'待支付（'+unPaidOrderNum+'）'"></a-tab-pane>
      <a-tab-pane key="UNDELIVERED" :title="'待发货（'+unDeliveredOrderNum+'）'"></a-tab-pane>
      <a-tab-pane key="PARTS_DELIVERED" :title="'部分发货（'+partsDeliveredOrderNum+'）'"></a-tab-pane>
      <a-tab-pane key="DELIVERED" :title="'待收货（'+deliveredOrderNum+'）'"></a-tab-pane>
      <a-tab-pane key="TAKE" :title="'待使用（'+unTakeOrderNum+'）'"></a-tab-pane>
<!--      <a-tab-pane key="REFUSE" title="售后中"></a-tab-pane>-->
      <a-tab-pane key="COMPLETED" title="已完成"></a-tab-pane>
      <a-tab-pane key="CANCELLED" title="已关闭"></a-tab-pane>
    </a-tabs>
    <!-- 搜索 -->
    <!--<searchTable ref="searchTableRef" :columns="columnsSearch" @reset="(val) => {apiParams = {...apiParams, ...val}}" @search="(val) => {apiParams = {...apiParams, ...val}}"></searchTable>-->
    <searchTable
      ref="searchTableRef"
      :columns="columnsSearch"
      @reset="tableReset"
      @search="tableSearch"
    ></searchTable>
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">

        <a-space>
          <a-popover title="核验码" trigger="click" position="bl">
            <a-button type="primary">核验订单</a-button>
            <template #content>
              <div class="popover-content">
                <a-input v-model="qrCode" :style="{ width: '320px' }"></a-input>
                <a-button
                    :style="{ marginLeft: '10px' }"
                    type="primary"
                    @click="orderVerification"
                >查询</a-button
                >
              </div>
            </template>
          </a-popover>
          <a-button type="primary" @click="expressOrderDeliver">
            批量发货
          </a-button>
          <a-button @click="exportOrder"> 待发货订单 </a-button>
        </a-space>
      </a-col>
    </a-row>
    <div class="order-box">
      <div class="order-tab">
        <p style="width: 40%">商品信息</p>
        <p style="width: 10%">订单来源</p>
        <p style="width: 10%">应付</p>
        <p style="width: 8%;text-align: left;">买家ID</p>
        <p style="width: 8%;text-align: left;">买家/收货人</p>
        <p style="width: 8%">订单促销类型</p>
        <p style="width: 8%">订单状态</p>
        <p style="width: 8%">操作</p>
      </div>
      <div class="order-lists">
        <div
          v-for="(order, orderIndex) in columnsTableList"
          :key="orderIndex"
          class="order-item"
        >
          <div class="header">
            <p>
              订单编号：
              <a-typography-text copyable bold>
                <span style="color: #333">{{order.sn}}</span>
              </a-typography-text>
            </p>
            <p
              >下单时间：<span style="color: #333">{{
                order.createTime
              }}</span></p
            >
            <!--<p class="delete-order"></p>-->
          </div>
          <div class="body">
            <div style="width: 40%">
              <div class="goods">
                <div
                  v-for="(goods, goodsIndex) in order.orderItems"
                  :key="goodsIndex"
                >
                  <img class="hover-color" :src="goods.image" alt="" />
                  <div class="goods-info">
                    <div style="width: 100%" class="hover-color"
                      ><a-typography-text bold>{{
                        goods.name
                      }}</a-typography-text></div
                    >
                    <!--<div class="tag"></div>-->
                  </div>
                  <div class="goods-num">
                    <span class="global_color">
                      {{ unitPrice( goods.goodsPrice , '￥') }}
                    </span>
                    <span style="color: red"> x{{ goods.num }} </span>
                  </div>
                </div>
              </div>
            </div>
            <div>

            </div>
            <div style="width: 10%; line-height: 32px">
              <a-badge
                style="margin-right: 5px"
                :color="customClientTypeList(order.clientType).color"
              ></a-badge
              >{{ customClientTypeList(order.clientType).label }}
            </div>
            <div style="width: 10%; line-height: 32px;" >{{
              unitPrice(order.flowPrice, '￥')
            }}</div>
            <div style="width: 8%; line-height: 20px; padding-right: 10px; word-wrap: break-word;">
              <div>{{order.memberId }}</div>
            </div>

            <div style="width: 8%;text-align: left;font-size: 13px;">
              <router-link :to="'/detail/member-detail?id='+ order.memberId"> 
                <a-typography-text type="primary" >{{order.memberName}}</a-typography-text> 
              </router-link> 
              <div>{{order.consigneeName }}</div>
              <div>{{order.consigneeMobile }}</div>
              <div>{{order.consigneeAddressPath }}&nbsp;{{order.consigneeDetail }}</div>
            </div>
            <div style="width: 8%; line-height: 32px">
              <a-badge
                  style="margin-right: 5px"
                  :color="orderPromotionTypeList(order.orderPromotionType).color"
              ></a-badge
              >{{ orderPromotionTypeList(order.orderPromotionType).label }}
            </div>
            <div style="width: 8%; line-height: 32px">
              <a-badge
                  style="margin-right: 5px"
                  :color="customOrderStatusList(order.orderStatus).color"
              ></a-badge
              >{{ customOrderStatusList(order.orderStatus).label }}
            </div>
            <div style="width: 8%;cursor: pointer;">
              <a-typography-text  type="primary"  @click="() =>
                $openWindow({
                      name: 'order-detail',
                      query: {
                        id: order.sn,
                      },
                    })">
                查看
              </a-typography-text>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="paginationBox">
      <a-pagination
        :total="paginationParams.total"
        show-page-size
        :current="previewParams.pageNumber"
        :page-size="previewParams.pageSize"
        @change="paginationChange"
        @page-size-change="
          (number) => {
            previewParams.pageSize = number;
            previewParams.pageNumber = 1;
          }
        "
      ></a-pagination>
    </div>

    <a-modal
      v-model:visible="importModal"
      title="导入批量发货信息"
      @ok="bulkDeliverySbumit"
      @cancel="false"
    >
      <div style="text-align: center">
        <a-upload
          draggable
          name="files"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :headers="{ accessToken: accessToken }"
          :action="action"
          :before-upload="handleUpload"
        >
        </a-upload>
        <a-button type="text" style="color: red" @click="downLoad"
          >下载导入模板</a-button
        >
      </div>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
import {
  downLoadDeliverExcel,
  getOrderList,
  queryExportOrder,
  uploadDeliverExcel,
  verificationCode,
  getOrderStatisticsVO
} from '@/api/order';
  import { exportExcel } from '@/components/excel/exportExcel';
  import searchTable from '@/components/search-column/index.vue';
  import { useUserStore } from '@/store';
  import { SearchRule } from '@/types/global';
  import { gatewayUrl } from '@/utils/axios';
  import store from '@/utils/storage';
  import { Message } from '@arco-design/web-vue';
  import { h, onMounted, reactive, ref, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import {
    deliveryMethod,
    afterSaleStatusList,
    orderType,
  } from '@/utils/tools';
  import getAssetsImages from '@/utils/assetsImages';
  import { unitPrice } from '@/utils/filters';

  const qrCode = ref('');

  // 携带toekn
  const accessToken = ref<string | any>(store.getAccessToken());
  const action = ref('');
  const flie = ref('');
  const userStore = useUserStore();
  const tablePageRef = ref('');
  const unPaidOrderNum = ref<any>(0);
  const unDeliveredOrderNum = ref<any>(0);
  const unTakeOrderNum = ref<any>(0);
  const partsDeliveredOrderNum = ref<any>(0);
  const deliveredOrderNum = ref<any>(0);
  const orderStatus = ref<string>('ALL')
  const apiParams = ref<any>({
    orderStatus:orderStatus.value
  });
  const searchTableRef = ref('');
  const router = useRouter();
  const selectList = ref([]);
  const importModal = ref(false); // 导入批量发货模态框
  // 查询海选列表
  const columnsSearch: Array<SearchRule> = [
    {label: '订单编号', model: 'orderSn', disabled: false, input: true,},
    {label: '下单时间', disabled: false, datePicker: {type: 'range',},},
    {label: '手机号后四位', model: 'consigneeMobile', disabled: false, input: true,},
    {label: '收件人姓名', model: 'shipName', disabled: false, input: true,},
    {label: '商品名称', model: 'goodsName', disabled: false, input: true,},
    {label: '订单促销类型', model: 'orderPromotionType', disabled: false, select: {options: orderType,},},
    // {label: '售后状态', model: 'afterSaleStatus', disabled: false, select: {options: afterSaleStatusList},},
    {label: '配送方式', model: 'deliveryMethod', disabled: false, select: {options: deliveryMethod,},}
  ];

  // 订单来源枚举
  const customClientTypeList = (type: string) => {
    let result = null as any;
    if (type === 'H5') {
      result = { value: 'H5', label: '移动端', color: 'purple' };
    } else if (type === 'PC') {
      result = { value: 'PC', label: 'PC端', color: 'blue' };
    } else if (type === 'WECHAT_MP') {
      result = { value: 'WECHAT_MP', label: '小程序端', color: 'green' };
    } else if (type === 'APP') {
      result = { value: 'APP', label: '移动应用端', color: 'magenta' };
    } else {
      result = {};
    }
    return result;
  };
  // 订单状态枚举
  const customOrderStatusList = (type: string) => {
    let result = null as any;
    if (type === 'UNDELIVERED') {
      result = { label: '待发货', value: 'UNDELIVERED', color: 'orange' };
    } else if (type === 'UNPAID') {
      result = { label: '未付款', value: 'UNPAID', color: 'magenta' };
    } else if (type === 'PAID') {
      result = { label: '已付款', value: 'PAID', color: 'blue' };
    } else if (type === 'DELIVERED') {
      result = { label: '待收货', value: 'DELIVERED', color: 'cyan' };
    } else if (type === 'PARTS_DELIVERED') {
      result = { label: '部分发货', value: 'PARTS_DELIVERED', color: 'cyan' };
    } else if (type === 'CANCELLED') {
      result = { label: '已取消', value: 'CANCELLED', color: 'red' };
    } else if (type === 'COMPLETED') {
      result = { label: '已完成', value: 'COMPLETED', color: 'green' };
    } else if (type === 'TAKE') {
      result = { label: '待使用', value: 'TAKE', color: 'orangered' };
    }  else {
      result = { label: '', value: '', color: '' };
    }
    return result;
  };
  // 订单促销类型枚举
  const orderPromotionTypeList = (type: string) => {
    let result = null as any;
    if (type === 'NORMAL') {
      result = {label: '普通订单', value: 'NORMAL', color: 'orange'};
    } else if (type === 'PINTUAN') {
      result = {label: '拼团订单', value: 'PINTUAN', color: 'magenta'};
    }else if (type === 'GIFT') {
      result = {label: '赠品订单', value: 'GIFT', color: 'blue'};
    }else if (type === 'VIRTUAL') {
      result = {label: '核验订单', value: 'VIRTUAL', color: 'red'};
    }else if (type === 'KANJIA') {
      result = {label: '砍价订单', value: 'KANJIA', color: 'green'};
    } else if (type === 'POINTS') {
      result = {label: '积分订单', value: 'POINTS', color: 'orangered'};
    } else {
      result = {label: '', value: '', color: ''};
    }
    return result;
  };
  const myColumns = [
    { title: '订单号', dataIndex: 'sn', width: 270 },
    { title: '订单来源', dataIndex: 'clientType', slotName: 'clientType' },
    { title: '买家名称', dataIndex: 'memberName' },
    { title: '订单金额', dataIndex: 'flowPrice', slotName: 'flowPrice' },
    { title: '订单状态', dataIndex: 'orderStatus', slotName: 'orderStatus' },
    { title: '下单时间', width: 200, dataIndex: 'createTime' },
    { title: '操作', slotName: 'options' },
  ];
  // 订单请求参数
  const previewParams = ref<any>({
    pageNumber: 1,
    pageSize: 20,
  });
  const rowSelection = ref<any>({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
    selectedRowKeys: [],
  });
  const selectedList = ref();
  const columnsTableList = ref();
  // 分页的属性配置
  const paginationParams = ref({
    total: 0,
  });
  // 订单的展开行配置
  const expandableColumnsTable = reactive({
    title: '',
    width: 80,
    slotName: 'extra',
    expandedRowRender: (record: any) => {
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      return h(
        'div',
        {
          style: { color: '', border: '' },
          class: 'my-expandable',
          id: '',
        },
        [
          // "render函数文本" 文本内容可以直接写入
          h('div', [
            h('div', { class: 'title' }, '商品详情'),
            record.orderItems.map((item: any) => {
              return h('div', { class: 'goods-detail' }, [
                h('img', { src: item.image }),
                h('div', [
                  h('p', item.name),
                  h('p', `x${item.num}`),
                  h('p', unitPrice(item.goodsPrice, '￥')),
                ]),
              ]);
            }),
            h('div', { class: 'flow-price' }, [
              h('span', '总价格'),
              h('span', unitPrice(record.flowPrice, '￥')),
            ]),
          ]), // h()创建的VNodes
          // h({template: `<div><div>${record.orderItems[0].sn}</div></div>`})
        ]
      );
      // return (JSON.stringify(record.orderItems))
    },
  });
  // 统计相关--订单统计
  const getMyOrder = async () => {
    const res = await getOrderList(previewParams.value);
    if (res.data.success) {
      columnsTableList.value = res.data.result.records;
      paginationParams.value = res.data.result;
    }
  };
  // 已选择的数据行发生改变时触发
  const selectTableChanges = (keys: Array<string | number>) => {
    rowSelection.value.selectedRowKeys = keys;
    selectedList.value = keys;
  };
  // 重置
  const tableReset = (val: any) => {
    previewParams.value.pageNumber = 1;
    previewParams.value = { ...previewParams.value, ...val };
  };
  // 搜索
  const tableSearch = (val: any) => {
    previewParams.value.pageNumber = 1;
    previewParams.value = { ...previewParams.value, ...val };
  };
  const paginationChange = (number: number) => {
    previewParams.value.pageNumber = number;
  };
  // 选择的行
  const selectTableChange = (val: any) => {
    selectList.value = val;
  };
  // 批量发货
  const expressOrderDeliver = () => {
    importModal.value = true;
    action.value = `${gatewayUrl}/order/order/batchDeliver`;
  };
  // 导出
  const exportOrder = () => {
    const params = {
      // 搜索框初始化对象
      pageNumber: 1, // 当前页数
      pageSize: 10000, // 页面大小
      sort: 'startDate', // 默认排序字段
      order: 'desc', // 默认排序方式
      startDate: '', // 起始时间
      endDate: '', // 终止时间
      orderSn: '',
      buyerName: '',
      tag: 'WAIT_SHIP',
      orderType: 'NORMAL',
      storeId: userStore.userInfo.id,
    };
    const exportTableData = ref([]);
    queryExportOrder(params).then((res) => {
      if (res.data.success) {
        if (res.data.result.length === 0) {
          Message.warning('暂无待发货订单');
        }
        exportTableData.value = res.data.result;
        const titleObj = {
          订单号: 'sn',
          收货人: 'consigneeName',
          收货人联系电话: 'consigneeMobile',
          收货地址: 'consigneeDetail',
          商品名称: 'goodsName',
          商品价格: 'goodsPrice',
          订单金额: 'flowPrice',
          商品数量: 'num',
          店铺名称: 'storeName',
          创建时间: 'createTime',
        };
        exportExcel(
          exportTableData.value,
          `待发货订单`,
          titleObj,
          '待发货订单'
        );
      } else {
        Message.warning('导出订单失败，请重试');
      }
    });
  };
  // 下载excel
  const downLoad = () => {
    downLoadDeliverExcel()
      .then((res: any) => {
        const blob = new Blob([res], {
          type: 'application/vnd.ms-excel;charset=utf-8',
        });
        // 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
        // IE10以上支持blob但是依然不支持download
        if ('download' in document.createElement('a')) {
          // 支持a标签download的浏览器
          const link = document.createElement('a'); // 创建a标签
          link.download = '批量发货导入模板.xls'; // a标签添加属性
          link.style.display = 'none';
          link.href = URL.createObjectURL(blob);
          document.body.appendChild(link);
          link.click(); // 执行下载
          URL.revokeObjectURL(link.href); // 释放url
          document.body.removeChild(link); // 释放标签
        } else {
          navigator.msSaveBlob(blob, '批量发货导入模板.xls');
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  // 上传文件
  const upload = async () => {
    const fd = new FormData();
    fd.append('files', flie.value);
    const res = await uploadDeliverExcel(fd);
    if (res.data.success) {
      Message.success('发货成功');
    }
  };
  // 上传数据
  const handleUpload = (file: any) => {
    file.value = file;
    upload();
  };
  // 批量发货确定
  const bulkDeliverySbumit = () => {
    importModal.value = false;
    getMyOrder();
  };
  // 核验订单
  const orderVerification = async () => {
    const res = await verificationCode(qrCode.value);
    if (res.data.success) {
      router.push({
        name: 'order-detail',
        query: { id: res.data.result.sn || qrCode.value },
      });
    }
  };
  const getOrderNum = async () => {
    const res = await getOrderStatisticsVO();
    if (res.data.success) {
      unPaidOrderNum.value = res.data.result.unPaidOrder;
      unDeliveredOrderNum.value = res.data.result.unDeliveredOrder;
      unTakeOrderNum.value = res.data.result.unTakeOrder;
      partsDeliveredOrderNum.value = res.data.result.partsDeliveredOrder;
      deliveredOrderNum.value = res.data.result.deliveredOrder;


    }
  };



  // 初始化监听
  watch(
    () => [previewParams.value],
    (val) => {
      getMyOrder();
    },
    { deep: true }
  );
  onMounted(() => {
    getMyOrder();
    getOrderNum();
  });
</script>

<style scoped lang="less">
  :deep(.my-expandable) {
    .title {
      font-size: 18px;
      line-height: 50px;
      font-weight: bold;
    }
    .order-detail {
      display: flex;
      flex-wrap: wrap;
      p {
        width: 300px;
        height: 40px;
        line-height: 40px;
        margin: 0;
        color: #666666;
        span:nth-of-type(1) {
          margin-right: 16px;
          font-weight: bold;
        }
      }
    }
    .goods-detail {
      display: flex;
      margin-bottom: 20px;
      img {
        width: 100px;
        height: 100px;
        border-radius: 10px;
      }
      > div {
        display: flex;
        flex-direction: column;
        justify-content: center;
        margin-left: 18px;
        p {
          margin: 0;
          line-height: 24px;
        }
        p:nth-of-type(3) {
          color: #ff0000;
          font-weight: bold;
        }
      }
    }
    .flow-price {
      text-align: right;
      padding-right: 20%;
      font-size: 16px;
      span:nth-of-type(1) {
        margin-right: 18px;
      }
      span:nth-of-type(2) {
        color: #ff0000;
        font-size: 24px;
        font-weight: bold;
      }
    }
  }
  .paginationBox {
    margin-top: 18px;
    display: flex;
    flex-direction: row-reverse;
  }

  .order-box {
    .order-tab {
      width: 100%;
      height: 50px;
      font-size: 14px;
      background-color: #f3f4f5;
      color: #252931;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      p {
        flex-shrink: 0;
        text-align: center;
      }
    }
    .order-lists {
      .order-item {
        box-sizing: border-box;
        border: 1px solid #eeeff0;
        margin-bottom: 10px;
        font-size: 14px;
        .header {
          width: 100%;
          height: 50px;
          background-color: #f8f9fa;
          color: #333;
          display: flex;
          align-items: center;
          box-sizing: border-box;
          padding: 0 20px;
          position: relative;
          font-size: 14px;
          p {
            margin-right: 30px;
          }
          .delete-order {
            position: absolute;
            top: 3px;
            right: 0;
            margin-right: 0;
          }
        }
        .body {
          display: flex;
          align-items: stretch;
          justify-content: space-between;
          text-align: center;
          color: #252931;
          > div {
            flex-shrink: 0;
            box-sizing: border-box;
            padding: 14px 0;
            /*border-left: 1px solid #e5e5e5;*/
          }
          > div:nth-of-type(1) {
            border-left: none;
            padding: 0;
            text-align: left;
          }
          .goods > div {
            width: 100%;
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            /*border-bottom: 1px solid #e5e5e5;*/
            box-sizing: border-box;
            padding: 10px;
            position: relative;
            img {
              width: 48px;
              height: 48px;
              flex-shrink: 0;
              border-radius: 4px;
            }
            .goods-info {
              flex-shrink: 1;
              width: 100%;
              box-sizing: border-box;
              padding: 0 15px;
              color: #252931;
              font-size: 14px;
              line-height: 18px;
              .tag {
                color: #aaaaaa;
                white-space: nowrap;
                margin-top: 12px;
                line-height: 12px;
                width: 100%;
                > span {
                  display: inline-block;
                }
                > span:nth-of-type(1) {
                  width: 126px;
                }
                > span:nth-of-type(3) {
                  color: #e4393c;
                  text-align: end;
                  position: absolute;
                  right: 10px;
                  bottom: 10px;
                }
              }
            }
            .goods-num {
              flex-shrink: 0;
              width: 25%;
              text-align: right;
            }
          }
          .goods > div:nth-last-of-type(1) {
            border-bottom: none;
          }
        }
      }
    }
  }
</style>
